#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-08-22 01:14:23
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

from web.handler.api import BaseApiHandler
from lib.tornado_routes import route
from tornado import gen
from tornado.web import asynchronous, stream_request_body
from web.models.api.dorm.accident import Accident
import os
import time
import libimg
import string

head_title = '图片上传'

upload_path = '../upload/'
tmp_path = '../tmp/'
tmp_type = ['image/png','image/jpeg', 'image/gif']
listuser = ['username']
listpasswd = ['passwd']




@route(r'api/image/upload/test/?',name='image_test')
class test(BaseApiHandler):
	def get(self):
		self.write('''<html><body>
<form method="POST" action="/api/image/upload/new/" enctype="multipart/form-data">
username field 1: <input name="username" type="text"><br>
passwd field 2: <input name="passwd" type="text"><br>
imagepath field 3: <input name="imagepath" type="text"><br>
top field 3: <input name="top" type="text"><br>
left field 3: <input name="left" type="text"><br>
width field 3: <input name="width" type="text"><br>
height field 3: <input name="height" type="text"><br>
dw field 3: <input name="dw" type="text"><br>
dh field 3: <input name="dh" type="text"><br>
imagefile #1: <input name="imagefile" type="file"><br>
<input type="submit">
</form>
</body></html>''')

@route(r'api/image/upload/new/?',name='image_new')
@stream_request_body 
class UploadFileHandler(BaseApiHandler):
	'''
	@title 图片上传
	@method post
	@param username 用户名 默认:''
	@param passwd 密码 默认：''
	@param imagepath 图片存放路径 默认：'自动生成'
	@param imagename 图片存放的文件名 默认：'自动生成'
	@param imagefile 图片文件 默认：''
	@param top 剪裁图片的上边距 可选
	@param left 剪裁图片的左边距 可选
	@param width 剪裁图片的宽度 可选
	@param height 剪裁图片的高度 可选
	@param dw 剪裁的宽度 可选
	@param dh 剪裁的高度 可选
	@retfield isOk 发布成功与否1成功0失败 
	@retfield path 图片的路径 
	@return {status:200, message:'', data:null}---status:500(系统错误)400(请传入必要参数)
	@description 图片上传
	'''

	def post(self):
		print self.tmp_files
		print self.tmp_field
		top = self.tmp_field.get('top')
		left = self.tmp_field.get('left')
		width = self.tmp_field.get('width')
		height = self.tmp_field.get('height')
		dw = self.tmp_field.get('dw')
		dh = self.tmp_field.get('dh')
		# top = ''.join(top.split('-'))
		# left = ''.join(left.split('-'))
		# width = ''.join(width.split('-'))
		# height = ''.join(height.split('-'))
		# dw = ''.join(dw.split('-'))
		# dh = ''.join(dh.split('-'))
		args = (top is None or top == '') \
			and (left is None or left == '') \
			and (width is None or width =='') \
			and (height is None or height == '') \
			and (dw is None or dw == '') \
			and (dh is None or dh == '') 
		fargs = (top is not None and top != '') \
			and (left is not None and left != '') \
			and (width is not None and width != '')\
			and (height is not None and height != '') \
			and (dw is not None and dw != '') \
			and (dh is not None and dh != '') 
		# if args and fargs
		if self.tmp_files.get('imagefile').get('type') not in tmp_type:
			self.write_fail(None, 400, '上传的文件类型不正确')
			return
		if not (args or fargs):
			self.write_fail(None, 400, '请输入正确的参数')
			return
		if self.tmp_field.get('username') not in listuser or self.tmp_field.get('passwd') not in listpasswd:
			self.write_fail(None, 400, '用户名密码错误')
			return
		if self.tmp_files.get('imagefile') is None:
			self.write_fail(None, 500, '请传入必要参数')
			return
		if self.tmp_field.get('imagepath') is None:
			self.tmp_field['imagepath'] = 'other/'
		elif '.' in self.tmp_field.get('imagepath'):
			self.write_fail(None, 500, '输入的路径不正确')
			return
		if self.tmp_field.get('imagename') is None:
			self.tmp_field['imagename'] = str((int)(time.time()*1000))
		elif '.' in self.tmp_field.get('imagename'):
			self.write_fail(None, 500, '输入的文件名不正确')
			return
		self.tmp_field['imagepath'] = os.path.join(upload_path
			, self.tmp_field.get('username'), self.tmp_field.get('imagepath'))
		

		if not os.path.exists(self.tmp_field.get('imagepath')):
			stmp = self.tmp_field.get('imagepath').replace('\\', '#')
			stmp = stmp.replace('/', '#')
			stmp = stmp.split('#')
			spath = []
			for i in stmp:
				spath.append(i)
				spath.append('/')
				p = ''.join(spath)
				if not os.path.exists(p):
					os.mkdir(p)
		self.tmp_field['imagename'] = self.tmp_field['imagename'] + '.' \
			+ self.tmp_files.get('imagefile').get('type').split('/')[1]
		savepath = os.path.join(self.tmp_field.get('imagepath'), self.tmp_field.get('imagename'))
		tmp_f = open(self.tmp_files.get('imagefile').get('path'), 'rb')
		img_f = open(savepath, 'wb+')
		img_f.write(tmp_f.read())
		img_f.close()
		tmp_f.close()

		if fargs:
			libimg.crop(string.atoi(left), string.atoi(top), string.atoi(width), 
				string.atoi(height), string.atoi(dw), string.atoi(dh), savepath, savepath)

		self.write_success({'isOk':1, 'path':'/api/' + self.tmp_field['username'] \
			+ '/uploads' + savepath.split(self.tmp_field.get('username'))[-1]})

	def on_finish(self):
		self.del_tmp_file()
		BaseApiHandler.on_finish(self)

	def prepare(self):
		try:
			total = int(self.request.headers.get("Content-Length","0"))
		except:
			total = 0

		self.contentType = '--' + self.request.headers.get("Content-Type").split('boundary=')[1] + '\r\n'
		self.endcontentType = '--' + self.request.headers.get("Content-Type").split('boundary=')[1] + '--'
		self.tmp_files = {}
		self.tmp_field = {}
		self.fname = ""
		self.tmp_file = None
		self.stmp = ""

	def data_received(self, chunk):
		# print chunk
		stmp = ''.join([self.stmp, chunk])
		if len(stmp.split(self.endcontentType)) == 1:
			if len(stmp.split(self.contentType)) == 1:
				stmp = self.stmp.split(self.contentType)
				self.stmp = chunk
			else:
				stmp = stmp.split(self.contentType)
				self.stmp = stmp[-1]
				stmp.remove(self.stmp)
		else:
			stmp = stmp.split(self.contentType)
			self.stmp = ''
		# print stmp
		# stmp = chunk.split(self.contentType)
		# print stmp
		for s in stmp:
			if s != '':
				writestr = s.split('\r\n\r\n')
				if 'Content-Disposition: form-data; name=' in writestr[0] :
					if self.tmp_file is not None:
						self.tmp_file.close()
						self.tmp_file = None
					try:
						for i in writestr[0].split('\r\n'):
							title = i.split(': ')
							if title[0] == 'Content-Disposition':
								self.fname = i.split('name="')[1].split('"')[0]
								self.tmp_files[self.fname] = {}
							elif title[0] == 'Content-Type':
								self.tmp_files[self.fname]['type'] = title[1]
						if 'type' in self.tmp_files[self.fname]:
							self.tmp_files[self.fname]['path'] = self.create_tmp_path()
						else:
							self.tmp_files.pop(self.fname)
							self.tmp_field[self.fname] = ""
					except Exception, e:
						pass
					if self.fname in self.tmp_files:
						for f in writestr[1:]:
							if self.endcontentType in f:
								self.tmp_file.write(''.join(f.split(self.endcontentType)))
								self.tmp_file.close()
							else:
								self.tmp_file.write(f)
					else:
						for f in writestr[1:]:
							if self.endcontentType not in f.split():
								self.tmp_field[self.fname] += ''.join(f.split())
							else:
								self.tmp_field[self.fname] += ''.join(f.split('\r\n'+self.endcontentType+'\r\n'))
				else:
					if self.fname in self.tmp_files:
						for f in writestr:
							if self.endcontentType in f:
								self.tmp_file.write(''.join(f.split(self.endcontentType)))
								self.tmp_file.close()
							else:
								self.tmp_file.write(f)
					else:
						for f in writestr:
							if self.endcontentType not in f.split():
								self.tmp_field[self.fname] += ''.join(f.split())
							else:
								self.tmp_field[self.fname] += ''.join(f.split('\r\n'+self.endcontentType+'\r\n'))
		# self.tmp_file.write(chunk)
		# self.ps.receive(chunk)
	def del_tmp_file(self):
		try:
			for i in self.tmp_files.keys():
				if 'type' in self.tmp_files[i]:
					os.remove(self.tmp_files[i]['path'])
		except Exception, e:
			pass

	def create_tmp_path(self):
		if not os.path.exists(tmp_path):
			os.mkdir(tmp_path)
		while True:
			tmp_file = os.path.join(tmp_path, str(time.time()))
			if not os.path.exists(tmp_file):
				self.tmp_file = open(tmp_file,"wb+")
				return tmp_file